package com.springboot.web;

import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RequestMapping("es")
@RestController
@Slf4j
public class IndexController {

    @Autowired
    private TransportClient transportClient;

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    @GetMapping("get/{index}/{type}/{id}")
    public ResponseEntity get(@PathVariable String index
                             ,@PathVariable String type
                             ,@PathVariable String id){

        GetResponse result = this.transportClient.prepareGet(index, type, id).get();

        log.info(result.getSourceAsString());

        return new ResponseEntity(result.getSource(), HttpStatus.OK);
    }

    @GetMapping("get2/{index}/{type}/{id}")
    public ResponseEntity getBySpingData(@PathVariable String index
            ,@PathVariable String type
            ,@PathVariable String id){

        GetResponse result = this.transportClient.prepareGet(index, type, id).get();


        NativeSearchQuery searchQuery = new NativeSearchQuery(QueryBuilders.matchQuery("id", id));


        List<String> strings = this.elasticsearchTemplate.queryForIds(searchQuery);

        log.info(result.getSourceAsString());

        return new ResponseEntity(strings, HttpStatus.OK);
    }

}
